package com.icongyou.enterprise.config.typehandler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.data_aggregation.entity.SubmissionEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 贡献度列表 TypeHandler
 * 用于将数据库中的 JSON 字符串转换为 List<SubmissionEntity.ContributionItem>
 * 注意：不再使用 @MappedTypes 全局注册，改为在需要的地方显式指定
 */
@Slf4j
public class ContributionRateTypeHandler extends BaseTypeHandler<List<SubmissionEntity.ContributionItem>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<SubmissionEntity.ContributionItem> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (Exception e) {
            throw new SQLException("Error converting List<ContributionItem> to JSON string", e);
        }
    }

    @Override
    public List<SubmissionEntity.ContributionItem> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public List<SubmissionEntity.ContributionItem> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public List<SubmissionEntity.ContributionItem> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    private List<SubmissionEntity.ContributionItem> parseJson(String json) {
        if (json == null || json.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(json, new TypeReference<List<SubmissionEntity.ContributionItem>>() {});
        } catch (Exception e) {
            log.error("Error parsing contribution_rate JSON: {}", json, e);
            return new ArrayList<>();
        }
    }
}
